<template>
    <view class="user" :style=" { paddingTop: paddingHeight + 'px' } ">
        <nav-bar title="个人信息"></nav-bar>
        <view style="padding-bottom: 200rpx;">
            <view class="cell small" style="margin: 16rpx 0;" :class=" { 'noClick': !clickType } ">
                <view
                    style="margin-top: 48rpx;"
                    @click="handleModal('name')"
                    :class=" { 'noClick': !clickType } "
                >
                    <u-input
                        placeholder="请输入"
                        color="#333333"
                        readonly
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" userInfo.name "
                    >
                        <view slot="prefix" class="prefix">
                            <text>姓名</text>
                        </view>
                    </u-input>
                </view>
                <view @click="handleModal('sex')">
                    <u-input
                        readonly
                        inputAlign="right"
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        v-model=" sex "
                    >
                        <view slot="prefix" class="prefix">
                            <text>性别</text>
                        </view>
                    </u-input>
                </view>
                <view @click="showDate = true">
                    <u-input
                        placeholder="请输入"
                        readonly
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" userInfo.age "
                    >
                        <view slot="prefix" class="prefix">
                            <text>年龄</text>
                        </view>
                    </u-input>
                </view>
                <view @click="handleModal('height')">
                    <u-input
                        placeholder="请输入"
                        readonly
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" userInfo.height "
                    >
                        <view slot="prefix" class="prefix">
                            <text>身高</text>
                        </view>
                        <view slot="suffix" class="suffix">
                            <text class="symbol">cm</text>
                            <!-- <text class="iconfont icon-arrow_rigth"></text> -->
                        </view>
                    </u-input>
                </view>

                <view @click="handleModal('weight')">
                    <u-input
                        placeholder="请输入"
                        readonly
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" userInfo.weight "
                    >
                        <view slot="prefix" class="prefix">
                            <text>体重</text>
                        </view>
                        <view slot="suffix" class="suffix">
                            <text class="symbol">kg</text>
                            <!-- <text class="iconfont icon-arrow_rigth"></text> -->
                        </view>
                    </u-input>
                </view>
                <view>
                    <u-input
                        placeholder="请输入"
                        type="number"
                        border="none"
                        inputAlign="right"
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        v-model=" userInfo.heartRate "
                    >
                        <view slot="prefix">
                            <text class="prefix">静息心率(次/min)</text>
                        </view>
                    </u-input>
                </view>
                <view @click=" palShowModal = true">
                    <u-input
                        readonly
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" userInfo.palName "
                    >
                        <view slot="prefix" class="prefix">
                            <text>运动强度</text>
                        </view>
                        <view slot="suffix" class="suffix">
                            <!-- <text class="symbol">kg</text> -->
                            <text class="iconfont icon-arrow_rigth"></text>
                        </view>
                    </u-input>
                </view>
                <view @click=" cookbookShowModal = true">
                    <u-input
                        readonly
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" userInfo.cuisineName "
                    >
                        <view slot="prefix" class="prefix">
                            <text>习惯的菜系</text>
                        </view>
                        <view slot="suffix" class="suffix">
                            <!-- <text class="symbol">kg</text> -->
                            <text class="iconfont icon-arrow_rigth"></text>
                        </view>
                    </u-input>
                </view>
                <view @click=" nativeShowModal = true">
                    <u-input
                        readonly
                        color="#333333"
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" userInfo.birthPlace "
                    >
                        <view slot="prefix" class="prefix">
                            <text>籍贯</text>
                        </view>
                        <view slot="suffix" class="suffix">
                            <!-- <text class="symbol">kg</text> -->
                            <text class="iconfont icon-arrow_rigth"></text>
                        </view>
                    </u-input>
                </view>
                <view @click=" goUpdateExhale ">
                    <u-input
                        color="#333333"
                        readonly
                        placeholderClass="placeholderClass"
                        shape="square"
                        border="none"
                        inputAlign="right"
                        v-model=" maxExhale "
                    >
                        <view slot="prefix" class="prefix">
                            <text>肺活量</text>
                        </view>
                        <view slot="suffix" class="suffix" style="margin-left: 8rpx;">
                            <u-image
                                v-if="userInfo.updateExhaleFlag == 1"
                                width="36rpx"
                                height="36rpx"
                                :showMenuByLongpress=" false "
                                src="http://oss.antaimedical.com/images/static/2024/06/666a5d71eb14d0f049f44d0dzLbneKYFW0kt589c345374b2007f538d1287127a5aae.png"
                                :lazy-load=" true "
                            ></u-image>
                            <text class="iconfont icon-arrow_rigth" style="margin-right:-8rpx;"></text>
                        </view>
                    </u-input>
                </view>
            </view>
        </view>
        <view class="btn-box">
            <view
                class="next-btn"
                style="margin: 0 auto;"
                @click="clickType = true"
                v-if="!clickType"
            >编辑</view>
            <template v-else>
                <view class="return-btn" @click="clickType = false">取消编辑</view>
                <view class="next-btn" @click=" updateFn ">提交编辑</view>
            </template>
        </view>
        <!-- 籍贯 -->
        <myPicker
            ref="uPicker"
            :show=" nativeShowModal "
            :columns=" provinceColumns "
            @close="nativeShowModal = false"
            closeOnClickOverlay
            @cancel="nativeShowModal = false"
            @confirm=" handleNativeConfirm "
            @change=" changeNative "
        ></myPicker>
        <!-- 菜系 -->
        <myPicker
            :show=" cookbookShowModal "
            :columns=" cookbookColumns "
            @close="cookbookShowModal = false"
            keyName="label"
            closeOnClickOverlay
            @cancel="cookbookShowModal = false"
            @confirm=" handleCookbookConfirm "
        ></myPicker>
        <!-- 运动强度 -->
        <myPicker
            :show=" palShowModal "
            :columns=" palCheckColumns "
            @close="palShowModal = false"
            keyName="label"
            closeOnClickOverlay
            @cancel="palShowModal = false"
            @confirm=" handlePalConfirm "
        ></myPicker>
        <timePop :showDate=" showDate " @close="showDate = false" @sendDate=" changeDate "></timePop>
        <custom-modal
            v-if="userInfo.id"
            :defaultWeight=" defaultWeight "
            :defaultHeight=" defaultHeight "
            :showModal=" showModal "
            :Psex=" userInfo.sex "
            :height=" userInfo.height "
            :weight=" userInfo.weight "
            :name=" userInfo.nickname "
            @close="showModal = false"
            @sendSex=" setSex "
            @sendName=" setName "
            :type=" type "
            @sendWeight=" setWeight "
            @sendHeight=" setHeight "
        ></custom-modal>
        <u-toast ref="uToast"></u-toast>
    </view>
</template>

<script>
import {
    getDetailsByUser,
    updateDetails
} from '@/api/index.js'
import timePop from '@/components/time-pop/index.vue'
import customModal from '@/components/custom-modal/index.vue'
import myPicker from '@/components/myPicker/myPicker.vue'
import { ProvinceList, CityList } from '@/utils/areaJson.js'
import {
    getCuisineMsg,
} from '@/api/index.js'
export default {
    data () {
        return {
            paddingHeight: uni.getStorageSync('navbarHeight'),
            imgUrl: this.$imgUrl,
            userId: uni.getStorageSync('userId'),
            showDate: false,
            showModal: false,
            type: '',
            defaultWeight: 65,
            defaultHeight: 175,
            nativeShowModal: false, //籍贯
            cookbookShowModal: false, //菜系
            palShowModal: false, //运动强度
            clickType: false,
            provinceColumns: [['北京市']],
            cookbookColumns: [],
            // 运动强度
            palCheckColumns: [[
                {
                    value: '1', label: '极低', hint: [
                        '静态生活方式/坐位工作，',
                        '很少或没有高强度的休闲活动'
                    ]
                },
                {
                    value: '2', label: '低', hint: [
                        '静态生活方式/坐位工作，',
                        '有时需要走动或站立，',
                        '但很少有高强度的休闲活动',
                    ]
                },
                {
                    value: '3', label: '中', hint: [
                        '主要是站着或走着工作',
                    ]
                },
                {
                    value: '4', label: '高', hint: [
                        '高强度职业工作或高强度，',
                        '休闲活动方式'
                    ]
                }
            ]
            ],
            palObj: {
                1: '极低',
                2: '低',
                3: '中',
                4: '高',
            },
            userInfo: {}, // 只读用户信息数据
            s_userInfo: {} // 可修改的数据

        }
    },
    components: {
        timePop,
        customModal,
        myPicker
    },
    watch: {
        'userInfo.sex': {
            handler (newVal, oldVal) {
                if (newVal == 2) {
                    this.defaultWeight = 50
                    this.defaultHeight = 160
                } else if (newVal == 1) {
                    this.defaultWeight = 65
                    this.defaultHeight = 175
                }
            }
        }
    },
    computed: {
        maxExhale () {
            return this.userInfo.maxExhale + 'ML'
        },
        sex () {
            return this.userInfo.sex == 1 ? '男' : '女'
        }
    },
    onShow () {
        this.getInfoByUser()
    },
    mounted () {
        this.provinceColumns.unshift(ProvinceList())
        this.getCuisineMsgData()
        this.$refs.uPicker.setColumnValues(1, CityList(0)) //初始化地区选择
    },
    methods: {
        // 获取菜系
        getCuisineMsgData () {
            getCuisineMsg().then((res) => {
                let arr = res.data.map((val) => {
                    return {
                        value: val.id,
                        label: val.cuisineName,
                    }
                })
                this.cookbookColumns.push(arr)
            })
        },
        // 地区选择 start
        handleNativeConfirm (v) {
            this.nativeShowModal = false
            this.s_userInfo.birthPlace = v.value[0] == v.value[1] ? v.value[0] : v.value[0] + v.value[1]
        },
        changeNative (e) {
            const {
                columnIndex,
                value,
                values, // values为当前变化列的数组内容
                index,
                // 微信小程序无法将picker实例传出来，只能通过ref操作
                picker = this.$refs.uPicker
            } = e
            if (columnIndex === 0) {
                // picker为选择器this实例，变化第二列对应的选项
                picker.setColumnValues(1, CityList(index))
            }
        },
        // 地区选择 end
        // 菜谱确定按钮
        handleCookbookConfirm (v) {
            this.cookbookShowModal = false
            this.s_userInfo.cuisineId = v.value[0].value
            this.s_userInfo.cuisineName = v.value[0].label
        },
        // 运动强度
        handlePalConfirm (v) {
            this.palShowModal = false
            this.s_userInfo.pal = v.value[0].value
            this.userInfo.palName = v.value[0].label
        },

        // 获取用户详情信息
        async getInfoByUser () {
            let params = {
                userId: this.userId,
                urlencoded: true
            }
            try {
                const res = await getDetailsByUser(params)
                if (res.code == 200) {
                    this.userInfo = res.data
                    this.userInfo['palName'] = this.palObj[this.userInfo.pal]
                    this.s_userInfo = res.data
                    this.$store.commit('setUserInfo', res.data)
                }
            } catch (e) {
                //TODO handle the exception
            }
        },
        // 计算年龄
        calculateAge (birthDateString) {
            var today = new Date();
            var birthDate = new Date(birthDateString);
            var age = today.getFullYear() - birthDate.getFullYear();
            var m = today.getMonth() - birthDate.getMonth();
            if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }
            return age;
        },
        changeDate (val) {
            // let info = {
            // 	key: 'birthday',
            // 	data: val.replace(/年|月/g, '-').replace(/日/g, '')
            // }
            let data = val.replace(/年|月/g, '-').replace(/日/g, '')
            let arr = data.split('-')
            let newarr = arr.map((item, index) => {
                if (index != 0) {
                    if (item.length <= 1) {
                        return '0' + item
                    } else {
                        return item
                    }
                } else {
                    return item
                }
            })
            // info.data = newarr.join('-')
            this.s_userInfo.birthday = newarr.join('-')
            this.userInfo.age = this.calculateAge(this.s_userInfo.birthday)
            this.showDate = false
        },
        // 改变刻度尺状态
        handleModal (type) {
            this.type = type
            this.showModal = true
        },
        setWeight (val) {
            this.s_userInfo.weight = String(val)
            this.showModal = false
            // let info = {
            // 	key: 'weight',
            // 	data: String(val)
            // }
        },
        setHeight (val) {
            this.s_userInfo.height = String(val)
            this.showModal = false
            // let info = {
            // 	key: 'height',
            // 	data: String(val)
            // }
        },
        setSex (val) {
            this.s_userInfo.sex = String(val)
            this.showModal = false
            // let info = {
            // 	key: 'sex',
            // 	data: String(val)
            // }
        },
        setName (val) {
            this.s_userInfo.name = String(val)
            this.showModal = false
            // let info = {
            // 	key: 'name',
            // 	data: String(val)
            // }
        },
        // 修改信息接口
        async updateFn (info) {
            let body = {
                userId: this.userId,
                id: this.userInfo.id,
                ...this.s_userInfo
            }
            body.heartRate = this.userInfo.heartRate
            // body[info.key] = info.data
            try {
                const res = await updateDetails(body)
                console.log(res)
                if (res.code == 200) {
                    this.clickType = false
                    uni.showToast({
                        title: '操作成功',
                        duration: 2000
                    })
                    this.getInfoByUser()
                } else {
                    this.$refs.uToast.show({
                        type: 'error',
                        icon: false,
                        message: res.msg,
                    })

                }
            } catch (e) {
                //TODO handle the exception
            }
        },
        goUpdateExhale () {
            uni.navigateTo({
                url: `/pagesB/my/userInfo/record`
            })
        }
    }
}
</script>
<style lang="scss">
page {
    background: #e3e8ff;
    min-height: 100vh;
}
</style>
<style lang="scss" scoped>
.noClick {
    pointer-events: none;
}

.btn-box {
    width: calc(100% - 150rpx);
    padding: 64rpx 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 114rpx;
    left: 50%;
    transform: translateX(-50%);

    .return-btn {
        width: 242rpx;
        height: 76rpx;
        background: #E3E8FF;
        border-radius: 32rpx;
        border: 4rpx solid #545dde;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 36rpx;
        color: #545dde;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .next-btn {
        width: 240rpx;
        height: 76rpx;
        background: #545dde;
        border-radius: 32rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 36rpx;
        color: #ffffff;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

.user {
    padding: 0 48rpx 48rpx;
    background: #e3e8ff;
    .cell {
        background: #ffffff;
        border-radius: 24rpx;
        padding: 0 32rpx;
        /deep/ .u-input {
            height: 112rpx;
            padding: 0 !important;
            border-radius: 16rpx !important;
            margin-top: 0;
            border-bottom: 2rpx solid #e6ebf5;
        }

        /deep/ .placeholderClass {
            font-size: 28rpx;
            color: rgba(102, 102, 102, 0.5);
        }

        .suffix,
        .prefix {
            display: flex;
            align-items: center;
            font-size: 32rpx;
            color: #666666;
        }

        .suffix {
            font-size: 28rpx;

            .symbol {
                color: #333333;
            }

            .icon-arrow_rigth {
                font-size: 36rpx;
                color: rgba(#666666, 0.5);
            }
        }

        .suffix_box {
            display: flex;
            align-items: center;

            .man,
            .woman {
                display: flex;
                align-items: center;

                .check_img {
                    width: 34rpx;
                    height: 34rpx;
                    margin-right: 16rpx;
                }

                text {
                    font-size: 28rpx;
                    color: #666666;
                }
            }

            .woman {
                margin-left: 30rpx;
            }
        }
    }

    .small {
        /deep/ .u-input {
            height: 108rpx;

            .u-input__content {
                line-height: 108rpx !important;
            }
        }
    }
}
</style>